package br.com.intelsys.basics.utils;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;

public class FieldMaskMaker {

	public final static Locale defaultLocale = new Locale("pt", "BR");

	public static String getNumberFieldFromMask(String number) {
		return number == null ? null : number.replaceAll("[^0-9]", "");
	}

	public static String getZipMask(String zip) {
		if (zip != null && zip.length() == 8) {
			return zip.substring(0, 5) + '-' + zip.substring(5, 8);
		}
		return null;
	}

	public static String getCpfMask(String cpf) {
		if (cpf != null && cpf.length() == 11) {
			return cpf.substring(0, 3) + '.' + cpf.substring(3, 6) + '.' + cpf.substring(6, 9) + '-' + cpf.substring(9, 11);
		}
		return null;
	}

	public static String getMoneyMask(BigDecimal money) {
		if (money != null) {
			NumberFormat formatter = NumberFormat.getCurrencyInstance(defaultLocale);
			return formatter.format(money.doubleValue());
		}
		return null;
	}

	public static String getMoneyNumberMask(BigDecimal money) {
		if (money != null) {
			try {
				NumberFormat formatter = NumberFormat.getCurrencyInstance(defaultLocale);
				String moneyStr = formatter.format(money.doubleValue());
				DecimalFormat decimalFormat = (DecimalFormat) NumberFormat.getInstance(defaultLocale);
				char decSep = decimalFormat.getDecimalFormatSymbols().getMonetaryDecimalSeparator();
				char groupSep = decimalFormat.getDecimalFormatSymbols().getGroupingSeparator();
				return moneyStr.replaceAll("[^0-9|\\" + decSep + "|\\" + groupSep + "]", "");
			} catch (Exception e) {
				return null;
			}
		}
		return null;
	}

	public static BigDecimal getMoneyFromMask(String money) {
		if (money != null && !money.isEmpty()) {
			NumberFormat formatter = NumberFormat.getCurrencyInstance(defaultLocale);
			try {
				Number number = formatter.parse(money);
				BigDecimal bd = new BigDecimal(number.doubleValue());
				return bd.setScale(2, BigDecimal.ROUND_HALF_EVEN);
			} catch (ParseException e) {
				try {
					DecimalFormat decimalFormat = (DecimalFormat) NumberFormat.getInstance(defaultLocale);
					char moneySep = decimalFormat.getDecimalFormatSymbols().getMonetaryDecimalSeparator();
					String noMask = money.replaceAll("[^0-9|\\" + moneySep + "]", "");
					BigDecimal bd = new BigDecimal(Double.parseDouble(noMask.replace(moneySep, '.')));
					return bd.setScale(2, BigDecimal.ROUND_HALF_EVEN);
				} catch (Exception e2) {
					return null;
				}
			}
		}
		return null;
	}

}
